//
//  ViewController.m
//  EpubInfo
//
//  Created by JM Zhao on 2018/1/3.
//  Copyright © 2018年 JunMing. All rights reserved.
//

#import "ViewController.h"
#import "SSZipArchive.h"
#import "FMDB.h"

@interface ViewController ()<SSZipArchiveDelegate>
@property (nonatomic, strong) FMDatabase *db;
@property (strong, nonatomic) IBOutlet UILabel *progress;
@property (strong, nonatomic) IBOutlet UILabel *total;
@property (strong, nonatomic) IBOutlet UILabel *unzip;
@property (strong, nonatomic) IBOutlet UIButton *startUnzip;

@property (nonatomic, assign) NSInteger totalN;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)startWriteData:(id)sender {
    
    [self insertInfo];
}

- (IBAction)start:(id)sender {
    

    [self unzipEpub];
}

// 获取数据插入数据库
- (void)insertInfo
{
    NSString *path = @"/Users/mac/Desktop/epub";
    NSFileManager *manger = [NSFileManager defaultManager];
    NSArray *array = [manger contentsOfDirectoryAtPath:path error:nil];
    _totalN = array.count;
    
    for (NSString *name in array) {
        
        if (![name isEqualToString:@".DS_Store"]) {
            
            NSDictionary *dic = [self getBookInfo:[path stringByAppendingPathComponent:name]];
            NSMutableDictionary *muDic = [dic mutableCopy];
            [muDic setValue:[NSString stringWithFormat:@"%@.epub", name] forKey:@"urlname"];
            [muDic setValue:@"120KB" forKey:@"size"];
            [self insertDate:[muDic copy]];
            
            _totalN--;
            NSLog(@"剩余: %ld", _totalN);
            
//            NSData *data = [NSData dataWithContentsOfFile:[bookPath stringByAppendingPathComponent:bookName]];
//            EpubBookModel *model = [[EpubBookModel alloc] init];
//            model.bookName = bookName;
//            model.bookSize = [self getBytesFromDataLength:data.length];
//            [model save];
//            NSLog(@"bookName:%@--bookSize:%ld", bookName, data.length);
        }
    }
}

- (void)insertDate:(NSDictionary *)info
{
    // 获得Documents目录路径
    NSString *sqlpath= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [sqlpath stringByAppendingPathComponent:@"epubInfo.sqlite"];
    self.db = [FMDatabase databaseWithPath:filePath];
    
    if ([self.db open]) {
    
        NSString *sqlCreat = [NSString stringWithFormat:@"create table if not exists t_EpubInfo (id integer primary key autoincrement, name text, urlname text, author text, cover text, size text, pages text, genre text, description text)"];
        BOOL isCreat = [_db executeUpdate:sqlCreat];
        NSLog(@"%@", isCreat?@"创建成功":@"创建失败");
        
        NSString *sqlInsert = [NSString stringWithFormat:@"insert into t_EpubInfo (name, urlname, author, cover, size, pages, genre, description) values ('%@','%@','%@','%@','%@','%@','%@','%@');", info[@"bookName"], info[@"urlname"], info[@"author"], info[@"cover"], info[@"size"], info[@"pages"], info[@"genre"], info[@"description"]];
        BOOL isInsert = [_db executeUpdate:sqlInsert];
        NSLog(@"%@", isInsert?@"插入成功":@"插入失败");
        [_db close];
    }
}

// 获取图书信息返回字段
- (NSDictionary *)getBookInfo:(NSString *)path
{
    // 先判断是否存在文件 iTunesMetadata.plist
    NSString *plist = [self findFields:path extension:@"plist"];
    
    // 不存在遍历查找 .opf 文件, 读取文件内容
    NSDictionary *dic;
    if (!plist) {
        
        NSString *opf = [self findFields:path extension:@"opf"];
        dic = [self getOpfContent:opf];
    }else{
        dic = [self getPlistContent:plist];
    }
    
    return dic;
}

- (NSDictionary *)getPlistContent:(NSString *)path
{
    //newsTest.plist文件
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
    
    // 遍历查找 cover.jpg
    NSString *str = [NSString stringWithFormat:@"/%@", path.lastPathComponent];
    NSString *cover = [self findFields:[path stringByReplacingOccurrencesOfString:str withString:@""] extension:@"jpg"];
    
    NSArray *desc = dic[@"playlistName"];
    NSString *title = dic[@"itemName"];
    NSString *creator = dic[@"artistName"];
    NSString *genre = dic[@"genre"];
    NSString *co = cover?[NSString stringWithFormat:@"%@-%@", dic[@"itemName"], cover.lastPathComponent]:@"null";
    
    if (cover) {
        
        NSError *error;
        NSFileManager *manger = [NSFileManager defaultManager];
        NSString *coverPath = @"/Users/mac/Desktop/covers";
        [manger copyItemAtPath:cover toPath:[coverPath stringByAppendingPathComponent:co] error:&error];
        NSLog(@"%@", error.description);
    }
    
    NSDictionary *dict = @{@"bookName":title?title:@"null", @"author":creator?creator:@"null", @"description":desc?desc:@"null", @"genre":genre?genre:@"null", @"cover":co};
    return dict;
}

// 读取opf 文件内容
- (NSDictionary *)getOpfContent:(NSString *)path
{
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSString *contrnt = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSArray *titles = [contrnt componentsSeparatedByString:@"dc:title"];
    NSArray *creators = [contrnt componentsSeparatedByString:@"dc:creator"];
    NSArray *descriptions = [contrnt componentsSeparatedByString:@"dc:description"];
    
    NSString *title = titles.count > 2 ? [titles[1] substringWithRange:NSMakeRange(1, [titles[1] length]-3)]:@"null";
    NSString *creator = creators.count>2 ? [creators[1] substringWithRange:NSMakeRange(1, [creators[1] length]-3)]:@"null";
    NSString *description = descriptions.count>2 ? [descriptions[1] substringWithRange:NSMakeRange(1, [descriptions[1] length]-3)]:@"null";
    
    // 遍历查找 cover.jpg
    NSString *str = [NSString stringWithFormat:@"/%@", path.lastPathComponent];
    NSString *cover = [self findFields:[path stringByReplacingOccurrencesOfString:str withString:@""] extension:@"jpg"];
    NSString *co = cover?[NSString stringWithFormat:@"%@-%@", title, cover.lastPathComponent]:@"null";
    
    if (cover) {
    
        NSError *error;
        NSFileManager *manger = [NSFileManager defaultManager];
        NSString *coverPath = @"/Users/mac/Desktop/covers";
        [manger copyItemAtPath:cover toPath:[coverPath stringByAppendingPathComponent:co] error:&error];
        NSLog(@"%@", error.description);
    }
    
    NSDictionary *dic = @{@"bookName":title?title:@"null", @"author":creator?creator:@"null", @"description":description?description:@"null", @"genre":@"null", @"cover":co};
    return dic;
}

// 遍历查找某文件, 找到返回文件路径
- (NSString *)findFields:(NSString *)path extension:(NSString *)ext
{
    BOOL dir = NO;
    NSFileManager *manger = [NSFileManager defaultManager];
    BOOL exist = [manger fileExistsAtPath:path isDirectory:&dir];
    if (!exist) {return nil;}
    
    if (dir) {
        
        NSString *final;
        NSArray *array = [manger contentsOfDirectoryAtPath:path error:nil];
        for (NSString *fileName in array) {
            
            NSString *filePath = [NSString stringWithFormat:@"%@/%@", path, fileName];
            final = [self findFields:filePath extension:ext];
            if (final) {return final;}
        }
        return final;
    }else{
        
        if ([ext isEqualToString:@"jpg"]) {
            
            NSString *extension = [[path pathExtension] lowercaseString];
            if ([extension isEqualToString:ext] || [extension isEqualToString:@"jpeg"]) {
                
                NSString *coverName = path.lastPathComponent.lowercaseString;
                if ([coverName isEqualToString:@"cover.jpg"] || [coverName isEqualToString:@"cover.jpeg"]) {
                
                    return path;
                }else{
                    
                    return nil;
                }
            }
            return nil;
        }else{
           
            NSString *extension = [[path pathExtension] lowercaseString];
            if ([extension isEqualToString:ext]) {return path;}
            return nil;
        }
    }
}

- (NSString *)getBytesFromDataLength:(NSInteger)dataLength {
    
    NSString *bytes;
    if (dataLength >= 0.1 * (1024 * 1024)) {
        bytes = [NSString stringWithFormat:@"%0.1f M",dataLength/1024/1024.0];
    } else if (dataLength >= 1024) {
        bytes = [NSString stringWithFormat:@"%0.0f K",dataLength/1024.0];
    } else {
        bytes = [NSString stringWithFormat:@"%zd B",dataLength];
    }
    return bytes;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 解压epub
- (void)unzipEpub
{
    NSString *path = @"/Users/mac/Desktop/epub";
    NSFileManager *manger = [NSFileManager defaultManager];
    NSArray *array = [manger contentsOfDirectoryAtPath:path error:nil];
    _totalN = array.count;
    
    for (NSString *name in array) {
        
        if (![name isEqualToString:@".DS_Store"]) {
            
            NSError *error;
            NSString *unzipPath = [path stringByAppendingPathComponent:name];
            NSString *desPath = [unzipPath stringByReplacingOccurrencesOfString:@".epub" withString:@""];
            BOOL isUzip = [SSZipArchive unzipFileAtPath:unzipPath toDestination:desPath delegate:self];
            NSLog(@"%@", isUzip?@"解压成功":@"解压失败");
            if (isUzip) {
                
                BOOL isDele = [manger removeItemAtPath:unzipPath error:&error];
                NSLog(@"%@", isDele?@"删除成功":@"删除失败");
            }
            
            _totalN--;
            NSLog(@"剩余: %ld", _totalN);
        }
    }
}

- (void)zipArchiveDidUnzipArchiveAtPath:(NSString *)path zipInfo:(unz_global_info)zipInfo unzippedPath:(NSString *)unzippedPath
{
    //    NSLog(@"%@--%@", path, unzippedPath);
}

@end
